package 栈;

import java.util.HashMap;
import java.util.Stack;

/**
 * @author XZ
 * @create 2021-04-23 20:33
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class _20_有效的括号 {
    private HashMap<Character, Character> map = new HashMap<>();

    public _20_有效的括号() {
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
    }

    /**
     * [({})]
     *
     * @param s
     * @return
     */
    public boolean isValid1(String s) {
        if (s.contains("{}") || s.contains("[]") || s.contains("()")) {
            s = s.replace("{}", "");
            s = s.replace("()", "");
            s = s.replace("[]", "");
        }
        return s.isEmpty();
    }

    public boolean isValid2(String s) {
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {//左字符
                stack.push(c);
            } else {//右字符
                if (stack.isEmpty()) return false;
                char left = stack.pop();
                if (left == '(' && c != ')') return false;
                if (left == '[' && c != ']') return false;
                if (left == '{' && c != '}') return false;
            }
        }
        return stack.isEmpty();
    }

    public boolean isValid3(String s) {
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {//左字符
                stack.push(c);
            } else {//右字符
                if (stack.isEmpty()) return false;
                char left = stack.pop();
                if (c != map.get(left)) return false;
            }
        }
        return stack.isEmpty();
    }


}
